package com.cn.goodsadmin.dao.impl;

import com.cn.goodsadmin.dao.BaseDao;
import com.cn.goodsadmin.dao.IUserAddressDao;
import com.cn.goodsadmin.po.Useraddress;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Repository("UserAddressDaoImpl")
public class UserAddressDaoImpl extends BaseDao<Useraddress> implements IUserAddressDao {
    public List<Useraddress> findUserAddress(final String openid, final int appid) throws Exception {
        final StringBuilder builder=new StringBuilder();
        builder.append("from Useraddress u where u.cAppid=?0");
        builder.append(" and u.cOpenid=?1");
        builder.append(" and u.cEnable=1");
        return getHibernateTemplate().execute(new HibernateCallback<List<Useraddress>>() {
            public List<Useraddress> doInHibernate(Session session) throws HibernateException {
                Query query=session.createQuery(builder.toString());
                query.setParameter(0,appid);
                query.setParameter(1,openid);
                return query.list();
            }
        });
    }

    public Useraddress findUserAddressByOpenidAndAdrress(final String openid,final int appid, final String address) throws Exception {
        final StringBuilder builder=new StringBuilder();
        builder.append("from Useraddress u where u.cAppid=?0");
        builder.append(" and u.cOpenid=?1");
        builder.append(" and u.cAddressname=?2");
        builder.append(" and u.cEnable=1");
        return getHibernateTemplate().execute(new HibernateCallback<Useraddress>() {
            public Useraddress doInHibernate(Session session) throws HibernateException {
                Query query=session.createQuery(builder.toString());
                query.setParameter(0,appid);
                query.setParameter(1,openid);
                query.setParameter(2,address);
                List<Useraddress> list=query.list();
                if(list!=null&&list.size()>0){
                    return list.get(0);
                }
                return null;
            }
        });
    }

    public Useraddress fidnUserAddressByID(int id) throws Exception {
        return get(Useraddress.class,id);
    }
}
